package cn.mju.tankfighterbackend.controller;

import cn.mju.tankfighterbackend.dao.CustomerUserRepository;
import cn.mju.tankfighterbackend.entity.CustomerUser;
import cn.mju.tankfighterbackend.service.TransactionalService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("test")
@CrossOrigin
public class TestController {


    @Autowired
    TransactionalService transactionalService;
    @Autowired
    CustomerUserRepository customerUserRepository;
    ExecutorService service = Executors.newFixedThreadPool(15);

    @RequestMapping("insertBach")
    public String insertBach() {
        for (int i = 0; i < 10; i++) {
            service.execute(() -> {
                Random random = new Random();
                for (int j = 0; j < 500; j++) {
                    transactionalService.invoke(()->{
                        insert("user:" + random.nextInt(100000));
                    }
                  );
                }
            });

        }
        service.shutdown();
        try {
            service.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @RequestMapping("check")
    public List<String> check() {
        List<String> users = new ArrayList<>();
        for (String repeatUser : customerUserRepository.findRepeatUsers()) {
            users.add(repeatUser);
        }
        return users;
    }

    @RequestMapping("init")
    public String init() {
        customerUserRepository.deleteAll();
        return "ok";
    }

    @Transactional
    public void insert(String username) {
        if (!customerUserRepository.existsByUserName(username)) {
            CustomerUser customerUser = new CustomerUser();
            customerUser.setUserName(username);
            customerUserRepository.save(customerUser);
        }
    }


}
